//
//  NGFirstViewController.m
//  NetMobileLocation
//
//  Created by Mehmet Sinan Şahin on 1/8/12.
//  Copyright (c) 2012 netgis. All rights reserved.
//

#import "NGMainViewController.h"
#import "NGUtility.h"
#import "NGLocation.h"
#import "Status.h"
#import "RotatingNGLocation.h"
#import "MainRow.h"
#import "NSDate+Extensions.h"
#import "NGLocationViewController.h"
#import "NGDBHelper.h"

@interface NGMainViewController()
- (void) refresh;
@end

@implementation NGMainViewController

@synthesize deviceID;
@synthesize logTable;
@synthesize displayedData;
@synthesize locations;



- (void) refresh {
    @synchronized(self) {
        if (locations) {
            [locations removeAllObjects];
            [locations release];
            locations = nil;
        }
        locations = [[NGDBHelper openDatabase] listLoggedLocations];
        [logTable reloadData];
    }
}
#pragma mark - table delegations

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Number of rows
    //Region *region = [regions objectAtIndex:section];
    //return [region.timeZoneWrappers count];

    //int count  = [self.displayedData count];
    int count = [self.locations count];
    return count;
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return @"";
    //Region *region = [regions objectAtIndex:section];
    //return [region name];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"NGLocation";
    //NGLocation *loc = [self.displayedData getElement:indexPath.row];
    NGLocation *loc = [self.locations objectAtIndex:indexPath.row];
    UITableViewCell *cell= [MainRow createCell:tableView cellIdentifier:cellIdentifier location:loc];
    return cell;
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
    
    NGLocation *loc = [self.locations objectAtIndex:indexPath.row];
    NGLocationViewController *locationView = [[[NGLocationViewController alloc] initWithNibName:@"NGLocationViewController" bundle:nil] autorelease];
    locationView.location = [loc retain];
    [self.view addSubview:locationView.view];
    [locationView viewWillAppear:FALSE];
    [loc release];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    
    @synchronized (self) {
        [self.logTable beginUpdates];
        [self.logTable visibleCells]; //calling for a bug in indexPathsForVisibleRows method
        NSArray *indexPathsForVisibleRows = [self.logTable indexPathsForVisibleRows];
        for (int i = 0; i < [indexPathsForVisibleRows count]; i++) {
            
            NSIndexPath *indexPath = [indexPathsForVisibleRows objectAtIndex:i];
            NSArray *indexPaths = [[NSArray alloc] initWithObjects:indexPath, nil];
            [self.logTable reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
            [indexPaths release];    
            
        }
        [self.logTable endUpdates];        
    }
}

#pragma mark - init

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = TTLocalizedString(@"Locations", @"");
        self.tabBarItem.image = [UIImage imageNamed:@"location-arrow"];
        /*
        self.displayedData = [[RotatingNGLocation alloc] initWithCapacity:MAX_VALUES_TO_BE_DISPLAYED];
        */
    }
    return self;
}

#pragma mark - Memory Warning

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    [locations release];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - NGLocationUpdated delegate method

-(void)updated:(NGLocation *)location {
    //[displayedData insertElement:location];
    [self refresh];
}

-(IBAction)clearLogs:(id)sender {
    
    UIAlertView *alert = [[UIAlertView alloc] 
                          initWithTitle: TTLocalizedString(@"DeleteAllLocationsTitle", @"")
                          message: TTLocalizedString(@"DeleteAllLocations", @"")
                          delegate: self
                          cancelButtonTitle: TTLocalizedString(@"Cancel", @"")
                          otherButtonTitles: TTLocalizedString(@"Delete", @""), nil];
    [alert show];
    [alert release];
}

// Called when delete all messages button is touched
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    switch (buttonIndex) {          
        case 1: {
            [[NGDBHelper openDatabase] deleteLocations:NGLOC_FORLOG];
            [self refresh];
        } break;
    }
}

#pragma mark - View lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];
    [deviceID setEditable:FALSE];
    [deviceID setText:[NGUtility getDeviceId]];
    [deviceID resignFirstResponder];
    
    logTable.delegate = self;
    logTable.dataSource = self;
	// Do any additional setup after loading the view, typically from a nib.
    
    //logTable.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg.png"]];
    [navItem setTitle:TTLocalizedString(@"Locations", @"")];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [self refresh];
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}


- (void)dealloc
{
    [deviceID release];
    [logTable release];
    if (locations != nil) [locations release];
    [displayedData release];
    [navItem release];
    [super dealloc];
}

@end
